﻿using AutoMapper;
using HealthcareSystem.API.Read.Application.Command;
using HealthcareSystem.API.Read.DTO;
using HealthcareSystem.Domain;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WeekExam.PassPort.ErrorCode;
using WeekExam.PassPort.Infrastructure.Interface;

namespace HealthcareSystem.API.Read.Application.CommandHandel
{
    /// <summary>
    /// 显示处理方法
    /// </summary>
    public class RecordCommandHand:IRequestHandler<RecordCommand,ApiResult<ApiPaging<List<RecordDTO>>>>
    {
        /// <summary>
        /// 居民列表仓储
        /// </summary>
        IBaseRepository<Record> recordRep;
        /// <summary>
        /// AUtomapping
        /// </summary>
        IMapper mapper;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="recordRep">居民列表仓储</param>
        /// <param name="mapper">AUtomapping</param>
        public RecordCommandHand(IBaseRepository<Record> recordRep, IMapper mapper)
        {
            this.recordRep = recordRep;
            this.mapper = mapper;
        }

        public async Task<ApiResult<ApiPaging<List<RecordDTO>>>> Handle(RecordCommand request, CancellationToken cancellationToken)
        {
            var list = recordRep.GetAll();
            if (!string.IsNullOrEmpty(request.RecordName))
            {
                list = list.Where(x => x.RecordName.Contains(request.RecordName));
            }
            var totalCount=await list.CountAsync();
            var pageCount=(int)Math.Ceiling(totalCount*1.0/request.PageSize);
            list=list.Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize);
            var listdto = mapper.Map<List<RecordDTO>>(list);
            return new ApiResult<ApiPaging<List<RecordDTO>>>
            {
                Code = ResultCode.Success,
                Message = "",
                Data = new ApiPaging<List<RecordDTO>>
                {
                    totalCount = totalCount,
                    totalPage = pageCount,
                    Data = listdto
                }
            };
        }
    }
}
